package com.xuzimian.globaldemo.thirdplatform.wechat.util;

import com.xuzimian.globaldemo.thirdplatform.wechat.config.WechatOpenProperties;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

@Service
@EnableConfigurationProperties({WechatOpenProperties.class})
public class WxJavaHelper {

    @Autowired
    private WechatOpenProperties wechatOpenProperties;

    private static class WxMpServiceHoler {
        private static WxMpService INSTANCE = new WxMpServiceImpl();
    }

    public WxMpService getWxService() {
        if (null == WxMpServiceHoler.INSTANCE.getWxMpConfigStorage()) {
            initWxMpService();
        }
        return WxMpServiceHoler.INSTANCE;
    }

    /**
     * @description 该方法需要单独去实现，这里是采用从springboot配置文件中自动装配类获取的。根据实际项目可制定适合的方式。
     */
    private void initWxMpService(){
        WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
        config.setAppId(wechatOpenProperties.getComponentAppId()); // 设置微信公众号的appid
        config.setSecret(wechatOpenProperties.getComponentSecret()); // 设置微信公众号的app corpSecret
        config.setToken(wechatOpenProperties.getComponentToken()); // 设置微信公众号的token
        config.setAesKey(wechatOpenProperties.getComponentAesKey()); // 设置微信公众号的EncodingAESKey
        WxMpServiceHoler.INSTANCE.setWxMpConfigStorage(config);
    }


}
